$(document).ready(function () {
	function showError(str,delay){	
		  if(delay){
			  $('#alertMessage').removeClass('success info warning').addClass('error').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500,function(){
					  $(this).delay(delay).animate({ opacity: 0,right: '-20'}, 500,function(){ $(this).hide(); });																														   																											
				});
			  return false;
		  }
			  	$('#alertMessage').addClass('error').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500);	
	  }
	  function showSuccess(str,delay){
		  if(delay){
			  $('#alertMessage').removeClass('error info warning').addClass('success').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500,function(){
					  $(this).delay(delay).animate({ opacity: 0,right: '-20'}, 500,function(){ $(this).hide(); });																														   																											
				});
			  return false;
		  }
			  $('#alertMessage').addClass('success').html(str).stop(true,true).show().animate({ opacity: 1,right: '10'}, 500);	
	  }
	var list_id = '';
	var host_name = 'SaleManagement'
	$(function() {
		var timer;
		$(".search_vendor").keyup(function(){
			clearTimeout(timer);
			var ms = 500;
			var q = $(this).val();
			if (q.length >= 2)
			{
				var dataString = "q=" + q ;
				$("#result_vendor").html("<img src='../img/loadder/loader_green.gif'/>");
				timer = setTimeout(function() {
			    $.ajax({
			        type: "GET",
			        url: "search_vendor",
			        data: dataString,
			        dataType: 'html',
			        success: function (data) {
			            $("#result_vendor").html(data).hide().fadeIn();
			        }
			    })},ms)
			}
		})
	})
	
	$(function() {
		var timer;
		$(".search_product").keyup(function(){
			clearTimeout(timer);
			var ms = 500;
			var q = $(this).val();
			if (q.length >= 2)
			{
				var dataString = "q=" + q ;
				$("#result_product").html("<img src='../img/loadder/loader_green.gif'/>");
				timer = setTimeout(function() {
			    $.ajax({
			        type: "GET",
			        url: "search_product",
			        data: dataString,
			        dataType: 'html',
			        success: function (data) {
			            $("#result_product").html(data).hide().fadeIn();
			        }
			    })},ms)
			}
		})
	})
	
	
	$(".choose_vendor").live("change", function(){
		$('#search_vendor').validationEngine('hide');
		var id = $(this).val().substr(0,$(this).val().length - 7);
		var dataString = "id=" + id ;
		$("#result_choose_vendor").html("<img src='../img/loadder/loader_green.gif'/>");
		$.ajax({
	        type: "GET",
	        url: "choose_vendor",
	        data: dataString,
	        dataType: 'html',
	        success: function (data) {
	            $("#result_choose_vendor").html(data).hide().fadeIn();
	        }
	    })
	})
	
	
	$(".choose_product").live("change", function(){
		$('#search_product').validationEngine('hide');
		var id = $(this).val().substr(0,$(this).val().length - 8);
		n = list_id.indexOf(id);
		if (n == -1) {
			var dataString = "id=" + id ;
			$("#result_choose_product").html("<img src='../img/loadder/loader_green.gif'/>");
			$.ajax({
		        type: "GET",
		        url: "choose_product",
		        data: dataString,
		        dataType: 'html',
		        success: function (data) {
					list_id = list_id + id + ',';
		            $("#result_choose_product").html(data).hide().fadeIn();
		            $("#result_choose_product").attr('id',id+'_product');
		            $("#list_product").append("<div id='result_choose_product'></div>");		             
		            $('.numericonly input').autotab_magic().autotab_filter('numeric');
		            $('form#validation').validationEngine();
		        }
		    })
		}
		else
		{
			showError("Đã thêm sản phẩm này",1000)
		}
		
	})
	
	$(".remove_product").live("click", function(){
		var id = $(this).attr('id').substr(0,$(this).attr('id').length-7);
		list_id = list_id.replace(id + ',','');
		showSuccess('Đã xóa sản phẩm',1000);
		$("#" + id + "_product").remove();
	})
	
	$("#create_wh_invoice").live("click", function(){
		var list_price = '';
		var list_quantity = '';
		var vendor = $(".vendor_id").attr("id");
		if (vendor == null)
			{
			$('#search_vendor').validationEngine('showPrompt', 'Chọn đối tác hoặc thêm đối tác mới!', 'pass');
			showError('Chọn đối tác hoặc thêm đối tác mới!',1000);
			}
		else
			{
			if (list_id == '')
				{
				$('#search_product').validationEngine('showPrompt', 'Chọn sản phẩm hoặc thêm mới sản phẩm', 'pass','topLeft');
				showError('Chọn sản phẩm hoặc thêm mới sản phẩm!',1000);
				$('#search_vendor').validationEngine('hide');
				}
			else
				{
					$('#search_vendor').validationEngine('hide');
					$('#search_product').validationEngine('hide');
					if($("#list_product").validationEngine('validate'))
					{
						var list_id_temp = list_id.substr(0,list_id.length-1);
						var array_id = list_id_temp.split(',');
						for (var i=0; i < array_id.length; i++)
						{
							id = array_id[i];
							list_price = list_price + $("#" + id + "_cost").val() + ',';
							list_quantity = list_quantity + $("#" + id + '_quantity').val() + ',';
						}
						var dataString = "list_id=" + list_id + "&vendor=" + vendor + "&list_quantity=" + list_quantity + "&list_price=" + list_price ;
						$.ajax({
					        type: "GET",
					        url: "create_warehouse_invoice",
					        data: dataString,
					        dataType: 'html',
					        success: function (data) {
					        	showSuccess('Tạo hóa đơn thành công',1000);
					            window.location.href= '/' + host_name + '/managers/warehouse?id=' + data
					        }
					    })
					}
					else
						{
							$("#list_product").validationEngine('validate')
						}
				}
			}		
	})
	
	$('.new_vendor').live("click", function() {
		if($(".newVendor").validationEngine('validate'))
			{
				var name = $("#vendor_name").val();
				var store = $("#vendor_store").val();
				var address = $("#vendor_address").val();
				var mobile = $("#vendor_mobile").val();
				var phone = $("#vendor_phone").val();
				var dataString = "name=" + name + "&store=" + store + "&address=" + address + "&phone=" + phone + "&mobile=" + mobile ;
				$("#result_choose_vendor").html("<img src='../img/loadder/loader_green.gif'/>");
				$.ajax({
			        type: "GET",
			        url: "new_vendor",
			        data: dataString,
			        dataType: 'html',
			        success: function (data) {
			        	showSuccess('Đã thêm đối tác mới',1000);
		        		$(".newVendor").fadeOut();
			        	var dataString2 = "id=" + data ;
						$.ajax({
					        type: "GET",
					        url: "choose_vendor",
					        data: dataString2,
					        dataType: 'html',
					        success: function (data) {
					            $("#result_choose_vendor").html(data).hide().fadeIn();
					        }
						})
			        }
			    })
			}
		else
			{
			$('.newVendor').validationEngine('validate');
			}
	})
	
	
	$(".add_product").live("click", function(){
		if($(".newProduct").validationEngine('validate'))
			{
			var name = $("#product_name").val();
			var type = $("#product_type").val();
			var unit = $("#product_unit").val();
			$("#alert_product").html("<img src='../img/loadder/loader_green.gif'/>");
			var dataString = "name=" + name + "&unit=" + unit + "&type=" + type;
			$.ajax({
		        type: "GET",
		        url: "new_product",
		        data: dataString,
		        dataType: 'html',
		        success: function (data2) {
		        	showSuccess('Đã thêm sản phẩm mới',1000);
					$("#result_choose_product").html("<img src='../img/loadder/loader_green.gif'/>");
					$(".newProduct").fadeOut();
					var dataString2 = "id=" + data2 ;
					$.ajax({
				        type: "GET",
				        url: "choose_product",
				        data: dataString2,
				        dataType: 'html',
				        success: function (data) {
							list_id = list_id + data2 + ',';
				            $("#result_choose_product").html(data).hide().fadeIn();
				            $("#result_choose_product").attr('id',data2+'_product');
				            $("#list_product").append("<div id='result_choose_product'></div>");
				            $('form#validation').validationEngine();
				        }
				    })
		        }
			})			
			}
		else
			{
				$(".newProduct").validationEngine('validate');
			}
		
	})
	
	
	$(".onChange").live("keyup",function() {
		var id = "" 
		if ($(this).attr("id").substr($(this).attr("id").length - 2, $(this).attr("id").length)== "ty" )
		{
			id = $(this).attr('id').substr(0,$(this).attr('id').length-9); 
		}
		else
		{
			id = $(this).attr('id').substr(0,$(this).attr('id').length-5);
		}
		if ($("#" + id + "_quantity") != "" && $("#" + id + "_cost") != "")
		{
			var sum = ""
			sum = $("#" + id + "_quantity").val() * $("#" + id + "_cost").val(); 
			$("#" + id + "_sum").val(sum)
		}
		var list_id_temp = list_id.substr(0,list_id.length-1);
		var array_id = list_id_temp.split(',');
		var total = parseInt(0,10);
		for (var i=0; i < array_id.length; i++)
		{
			id = array_id[i];
			total += parseInt($("#" + id + "_sum").val())
		}
		$("#sum_result").html(total)
	})
	
	
	
})

